<?php

namespace App\Console\Stats\Platform\Settlement\Task;

use App\Console\Stats\Command;
use App\Exceptions\Response\ServiceException;
use App\Models\Admin\Stats\Platform\Settlement\Day as StatsDay;
use App\Models\Admin\StatsTask\Platform\Settlement\Month as Task;
use Helper\Timed;

class Month extends Command
{

    /**
     * 控制台命令 signature 的名称。
     *
     * @var string
     */
    protected $signature = 'stats:platform:settlement:task:month {timed?}';

    /**
     * 控制台命令说明。
     *
     * @var string
     */
    protected $description = '【平台收益】创建统计任务【月】';

    /**
     * 执行控制台命令。
     *
     * @return mixed
     */
    public function handle()
    {
        try {
            $timed = $this->getMonthTimed();

            $this->info($this->description . date('Y-m-d H:i:s', $timed));

            if (Task::verifyTaskExist($timed)) {
                throw new ServiceException(ServiceException::SERVICE_EXISTED_DATA);
            }

            // 获取有记录的平台
            $datas = StatsDay::getStatsDistinct($timed, Timed::getMonthNextTimed($timed), ['plat_code']);

            $this->info('创建任务中...');
            Task::dbConnection()->transaction(function () use ($datas, $timed) {
                Task::initTasks($timed, $datas->toArray());
            });
            $this->info('创建任务完成');

            $this->info('执行成功。');
        } catch (\Throwable $e) {
            $this->error($e->getMessage());
            $this->error('执行失败。');
            throw $e;
        }
    }
}
